package com.vincce.fitness.api;

import com.alibaba.fastjson.JSON;
import com.vincce.fitness.constant.Constant;
import com.vincce.fitness.core.util.AccountUtil;
import com.vincce.fitness.core.util.CheckUtil;
import com.vincce.fitness.entity.Account;
import com.vincce.fitness.entity.User;
import com.vincce.fitness.mappers.core.UserMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;

/**
 * Created by Administrator on 2014/11/27.
 */
@Service
public class UserService {

	@Resource
	UserMapper userMapper;

	@Resource
	WechatRunner wechatRunner;

	/**
	 * 添加微信用户
	 * @param openid
	 * @param accountNo
	 * @return
	 */
	public User insertOrUpdate(String openid,String accountNo){
		User user = userMapper.findUserByOpenId(openid);
		if(CheckUtil.isEmpty(user)){
			user = new User();
			user.setOpenid(openid);
			user.setSubscribe(Constant.USER_STATUS_SUBSCRIBE);
			user.setCreateTime(new Date());
			user.setUpdateTime(new Date());
			Account account = AccountUtil.map.get(accountNo);
			user.setWxId(account.getId());
			userMapper.addUser(user);
		}else {
			user.setSubscribe(Constant.USER_STATUS_SUBSCRIBE);
			user.setUpdateTime(new Date());
			userMapper.updateSubscribe(user);
		}
		return user;
	}

	/**
	 * 更改微信用户的关注状态
	 * @param user
	 */
	public void updateSubscribe(User user){
		user.setSubscribe(Constant.USER_STATUS_UNSUBSCRIBE);
		user.setUpdateTime(new Date());
		userMapper.updateSubscribe(user);
	}

	/**
	 * 高级接口获取微信用户信息
	 * @param user
	 * @return
	 */
	public User updateUserInfo(User user,Account account) throws IOException {
		String userInfo = wechatRunner.getUserInfo(user.getOpenid(),account);
		if(!CheckUtil.isEmpty(userInfo)){
			User u = JSON.parseObject(userInfo,User.class);
			user.setSubscribe(u.getSubscribe());
			user.setNickname(u.getNickname());
			user.setSex(u.getSex());
			user.setCity(u.getCity());
			user.setCountry(u.getCountry());
			user.setProvince(u.getProvince());
			user.setLanguage(u.getLanguage());
			user.setHeadimgurl(u.getHeadimgurl());
			user.setSubscribeTime(u.getSubscribeTime());
			user.setUnionid(u.getUnionid());
			user.setUpdateTime(new Date());
			userMapper.updateUserInfo(u);
		}
		return user;
	}

}
